package Network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UDPEchoServer {
    private DatagramSocket socket = null;

    // 确定服务器port
    public UDPEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！！！");

        while(true) {
            //1.读取请求并响应
            //需要一个空盘子来等待接收数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);//二进制
            socket.receive(requestPacket);
            //为了后序在java中方便识别并且方便打印出来 需要转化成String类型
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());

            //2.根据请求计算响应
            String response  = process(request);
            //3.把响应写回客户端
            DatagramPacket responsePacker = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacker);

            System.out.printf("[%s:%d] req = %s,resp= %s\n",requestPacket.getAddress(),requestPacket.getPort(),
                    request,response);

        }

    }

    public  String process(String request) {
        return  request;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoServer server = new UDPEchoServer(9090);
        server.start();
    }
}




